//
//  CommentsCell.m
//  friendCyc
//
//  Created by roiland on 13-3-28.
//  Copyright (c) 2013年 sun. All rights reserved.
//

#import "CommentsCell.h"
#import "FirCirCommentInfo.h"
#import "SpeexCodec.h"
#import "FirCirLocalResourceDataSource.h"
#import "FirCirCommentDataSource.h"
#import "FirCirNewsDataSource.h"

@interface CommentsCell()
- (void)ImageBtnClicked:(id)sender;
@end;

@implementation CommentsCell

@synthesize comments,commentsAnchor,commentsContent,headPhoto,timeLabel,centerimageView,imgPhoto,commentsbtn;

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        // Initialization code
        
        //为背景预留
        centerimageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 320, 220)];
        [self addSubview:centerimageView];
        
        commentsContent = [[UILabel alloc]init];
        [commentsContent setBackgroundColor:[UIColor clearColor]];
        [commentsContent setFrame:CGRectMake(20, 28, 280, 220)];
        [commentsContent setFont:[UIFont fontWithName:@"Arial" size:14]];
        [commentsContent setLineBreakMode:NSLineBreakByTruncatingTail];
        [self addSubview:commentsContent];
        
        imgPhoto = [UIButton buttonWithType:UIButtonTypeCustom];
        [imgPhoto setFrame:CGRectMake(0, 0, 0, 0)];
        [imgPhoto addTarget:self action:@selector(ImageBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
        [imgPhoto setBackgroundImage:[UIImage imageNamed:@"btn_audioPlay_press.png"] forState:UIControlStateNormal];
        [self addSubview:imgPhoto];
        
        headPhoto = [[UIImageView alloc]initWithFrame:CGRectMake(15, 5, 40, 40)];
        [headPhoto setImage:[UIImage imageNamed:@"touxiang_40x40.png"]];
        [self addSubview:headPhoto];
        
        commentsAnchor = [[UILabel alloc]initWithFrame:CGRectMake(60,5, 150, 30)];
        [commentsAnchor setText:@""];
        [commentsAnchor setFont:[UIFont fontWithName:@"Arial" size:14]];
        [commentsAnchor setBackgroundColor:[UIColor clearColor]];
        [commentsAnchor setTextColor:[UIColor colorWithRed:63/255.0 green:93/255.0 blue:133/255.0 alpha:1.0]];
        [self addSubview:commentsAnchor];
        
        timeLabel = [[UILabel alloc]initWithFrame:CGRectMake(210,5, 200, 30)];
        [timeLabel setText:@""];
        [timeLabel setFont:[UIFont fontWithName:@"Arial" size:14]];
        [timeLabel setBackgroundColor:[UIColor clearColor]];
        [timeLabel setTextColor:[UIColor colorWithRed:63/255.0 green:93/255.0 blue:133/255.0 alpha:1.0]];
        [self addSubview:timeLabel];
        
        commentsbtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [commentsbtn setFrame:CGRectMake(10,commentsContent.frame.size.height-30,70,32)];
        [commentsbtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, -25)];
        [commentsbtn setTitle:@"发表回复" forState:UIControlStateNormal];
        [commentsbtn.titleLabel setFont:[UIFont fontWithName:@"Arial" size:14]];
        [commentsbtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [commentsbtn addTarget:self action:@selector(BtnClicked) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:commentsbtn];
        
        player = nil;
    }
    return self;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

- (void)ImageBtnClicked:(id)sender
{
    if (player != nil && [player isPlaying]) {
        [player stop];
        [imgPhoto setBackgroundImage:[UIImage imageNamed:@"btn_audioPlay_press.png"]
                            forState:UIControlStateNormal];
    }
    else
    {
        AVAudioSession *session = [AVAudioSession sharedInstance];
        NSError *sessionError;
        [session setCategory:AVAudioSessionCategoryPlayback error:&sessionError];
        
        if(session == nil)
        {
            AS_LOG(@"Error creating session: %@", [sessionError description]);
        }
        else
            [session setActive:YES error:nil];
        NSError *playerError;
        NSData *SpeexData = [NSData dataWithContentsOfFile:
                             [[DataControl shareControl].fcLocalRecDS getRcLocalPathByID:comments.commentID]];
        NSData *NewPCMData = DecodeSpeexToWAVE(SpeexData);
        player = [[AVAudioPlayer alloc] initWithData:NewPCMData error:&playerError];
        player.delegate = self;
        AS_LOG(@"voice length is %f",player.duration);
        [player prepareToPlay];
        [player play];
        
        if ([NewPCMData length] > 0) {
            [imgPhoto setBackgroundImage:[UIImage imageNamed:@"btn_audioPause_press.png"]
                                forState:UIControlStateNormal];
        }
    }
}

- (void)resizeTheHeight
{
    CGFloat contentWidth = 280;
    
    UIFont *font = [UIFont fontWithName:@"Arial" size:14];
    
    CGSize size = [commentsContent.text sizeWithFont:font
                                   constrainedToSize:CGSizeMake(contentWidth, CGFLOAT_MAX)
                                       lineBreakMode:NSLineBreakByTruncatingTail];
    
    [commentsContent setFrame:CGRectMake(20, 28, 280, size.height + 60)];
    
    if (comments.stIndex == FCG_ONE_SOUND) {
        [imgPhoto setFrame:CGRectMake(0, 70, 72, 72)];
        [centerimageView setFrame:CGRectMake(0, 0, 320,  200)];
    }
    else if(comments.stIndex == FCG_ONE_TEXT)
    {
        [imgPhoto setFrame:CGRectMake(120, size.height, 0, 0)];
        [centerimageView setFrame:CGRectMake(0, 0, 320, size.height + 120)];
    }
    [commentsbtn setFrame:CGRectMake(230,centerimageView.frame.size.height - 28,70,32)];
    
}

- (void)reloadCell
{
    if (comments == nil) {
        return;
    }
    self.commentsContent.text = comments.content;
    
    if ([comments.speaker isEqualToString:comments.speakto]) {
        FirendInfo *fi = [[DataControl shareControl] SearchInfo:comments.speaker];
        if (fi != nil) {
            [commentsAnchor setText:fi.name];
        }
    }
    else
    {
        FirendInfo *fispeaker = [[DataControl shareControl] SearchInfo:comments.speaker];
        FirendInfo *fispeakto = [[DataControl shareControl] SearchInfo:comments.speakto];
        if (fispeaker != nil && fispeakto) {
            [commentsAnchor setText:[NSString stringWithFormat:@"%@ 对 %@ 说",
                                     fispeaker.name,fispeakto.name]];
        }
    }
    
    [timeLabel setText:[comments TurnTimeString]];
    
    NSString *imagepath = [[DataControl shareControl] SearchHeadImage:comments.speaker];
    if (![imagepath isEqualToString:@""]) {
        [headPhoto setImage:[UIImage imageWithContentsOfFile:imagepath]];
    }
    
    if (comments.stIndex == FCG_ONE_SOUND) {
        [commentsContent setHidden:YES];
    }
    
    [self resizeTheHeight];
}

#pragma mark -private fun-
-(void)BtnClicked
{
    if (comments == nil) {
        return;
    }
    
    [[DataControl shareControl].fccommentDS SetCommentSendInfo:comments.mail
                                                     withNewID:comments.newsID
                                                   withSpeakTo:comments.mail];
    
    [[ViewManager sharedViewManager] showView:VI_COMMENT
                             withIsRemoveCurV:false
                                withDirection:VD_RIGHT];
}

#pragma mark AVAudioPlayerDelegate

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer*)myplayer successfully:(BOOL)flag{
    [myplayer stop];
    [imgPhoto setBackgroundImage:[UIImage imageNamed:@"btn_audioPlay_press.png"]
                        forState:UIControlStateNormal];
}

@end
